﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CSProjectCodeLine
{
    class CodeCounter
    {
        private int codeLines;

        /// <summary>
        /// 代码行数
        /// </summary>
        public int CodeLines
        {
            get
            {
                return codeLines;
            }

            set
            {
                codeLines = value;
            }
        }

        private int commentLines;

        /// <summary>
        /// 注释行数
        /// </summary>
        public int CommentLines
        {
            get
            {
                return commentLines;
            }

            set
            {
                commentLines = value;
            }
        }

        private int fileNumber;

        /// <summary>
        /// 文件个数
        /// </summary>
        public int FileNumber
        {
            get
            {
                return fileNumber;
            }

            set
            {
                fileNumber = value;
            }
        }

        public CodeCounter()
        {
            codeLines = 0;
            commentLines = 0;
            fileNumber = 0;
        }

        /// <summary>
        /// 获取整个项目的代码统计情况
        /// </summary>
        /// <param name="folderPath"></param>
        public void GetProjectResult(string folderPath)
        {
            DirectoryInfo folder = new DirectoryInfo(folderPath);
            try
            {
                var folders = folder.GetDirectories();
                for (int i = 0; i < folders.Length; i++)
                {
                    //递归调用 有时候会碰到目录权限问题
                    GetProjectResult(folders[i].FullName);
                }

                var csFiles = folder.GetFiles("*.cs");
                for (int i = 0; i < csFiles.Length; i++)
                {
                    fileNumber++;
                    string fieleName = folderPath + "\\" + csFiles[i].Name;
                    GetCodeFileResult(fieleName);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 单个文件代码统计情况
        /// </summary>
        /// <param name="fileName"></param>
        public void GetCodeFileResult(string fileName)
        {
            string line;
            StreamReader sr = new StreamReader(fileName);
            while ((line = sr.ReadLine()) != null)
            {
                codeLines++;
            }
        }
    }
}
